
import {Component,OnInit,ChangeDetectorRef} from '@angular/core';
import { HttpService } from '../../../services/http.service';
import { Router } from '@angular/router';
import { ActionSheetController } from '@ionic/angular';
import { NotarizationInfoService } from '../../../services/notarization-info.service';
import { UpphotoService } from '../../../services/upphoto.service';
import { BaseUiService } from '../../../services/base-ui.service';
import { commService } from '../../../services/comm.service'
import { LoginInfoService } from '../../../services/login-info.service';
import { EventService } from '../../../services/QaService';
import { PickerController } from '@ionic/angular';
import { CityDataService } from '../../../services/city-data.service'

@Component({
  selector: 'app-online',
  templateUrl: './online.page.html',
  styleUrls: ['./online.page.scss'],
})
export class OnlinePage implements OnInit {
  public onlineTab = "tab1"
  public notaryList:any
  public notaryName:any
  public userInfo:any
  public imgList:any = [];
  public province = '';//省份
  public provinceCode = '';//省份Code
  public city = '';//城市
  public cityCode = '';//城市Code
  public notary = '';//公证处
  public notaryCode = '';//公证处Code
  public temPotaryList = [];
  constructor(
    public eventService:EventService,
    public LoginInfoService: LoginInfoService,
    public commService: commService,
    public baseUiService:BaseUiService,
    public upphotoService:UpphotoService,
    public router: Router,
    public HttpService: HttpService,
    public NotarizationInfoService:NotarizationInfoService,
    public actionSheetController: ActionSheetController,
    private pickerController: PickerController,
    public CityDataService: CityDataService,
    private cd: ChangeDetectorRef
  ) {}

  ngOnInit(){
    this.userInfo = this.LoginInfoService.getInfo();
  }
  seach(){
    
  }

  //获取省份
  public async openProvincePicker() {
    const picker = await this.pickerController.create({
      columns: this.getProvince(),
      buttons: [
        {
          text: '取消',
          role: 'cancel'
        },
        {
          text: '确定',
          handler: (value) => {
            this.province = value.province.text;
            this.provinceCode = value.province.value;
            this.cityCode = '';
            this.city = '';
            this.notary = '';
            this.notaryCode = ''; 
            console.log(value);
          }
        }
      ]
    });

    await picker.present();
  }

  private getProvince() {
    // ion-pick 有个问题，create方法接收的参数中columns 不能直接给对象字面量，必须每次调用create时动态创建一个新对象，即时将这个对象保存为组件对象的属性xxx，这里通过return this.xxx，这样的方式也不行，会导致第二次打开时样式不正常。
    return this.CityDataService.getProvince();
  }

  //获取城市
  public async openCityPicker() {
    if(this.province === ''){
      this.baseUiService.showToast('请先选择省份！','danger','top');
      return;
    }
    const picker = await this.pickerController.create({
      columns: this.getCity(),
      buttons: [
        {
          text: '取消',
          role: 'cancel'
        },
        {
          text: '确定',
          handler: (value) => {
            this.city = value.city.text;
            this.cityCode = value.city.value;
            this.notary = '';
            this.notaryCode = ''; 
          }
        }
      ]
    });
    await picker.present();
  }

  private getCity() {
    // ion-pick 有个问题，create方法接收的参数中columns 不能直接给对象字面量，必须每次调用create时动态创建一个新对象，即时将这个对象保存为组件对象的属性xxx，这里通过return this.xxx，这样的方式也不行，会导致第二次打开时样式不正常。
    
    let cityList = this.CityDataService.getCityS()[1].options;
    let arr = [];
    let info = {
      name: 'city',
      options: []
    }
    for(let i of cityList){
      if(i['parentVal'] == this.provinceCode){
        info.options.push(i);
      }
    }
    arr.push(info)
    return arr;
  }

  //  //获取公证处
   public async openNotaryPicker() {
    if(this.cityCode === ''){
      this.baseUiService.showToast('请先选择城市！','danger','top');
      return;
    }
    this.getNotary().then(
      async res =>{
        const picker = await this.pickerController.create({
          columns: this.temPotaryList,
          buttons: [
            {
              text: '取消',
              role: 'cancel'
            },
            {
              text: '确定',
              handler: (value) => {
                this.notary = value.notary.text;
                this.notaryCode = value.notary.value;
              }
            }
          ]
        });
        console.log(this.temPotaryList)
        console.log(this.temPotaryList.length)
        if(this.temPotaryList.length == 0){
          this.baseUiService.showToast('当前城市没有公证处','danger','top')
        }else{
          await picker.present();
        }
      }
    )
  }

  private getNotary() {
    this.temPotaryList = [];
   return new Promise((reslove,reject) => {
      let info = {
        name: 'notary',
        options: []
      }
      this.HttpService.GET_notaryOffice({cityCode: this.cityCode}).then(res=>{
        if(res["items"].length > 0){
          for(let i of res["items"]){
            let json = {
              text:'',
              value:''
            }
            json.text = i.notarialName;
            json.value = i.unitGuid;
            info.options.push(json);
          }
          this.temPotaryList.push(info);
        }
        reslove(this.temPotaryList)
      })
    })
  }

  //下一步
  goFlow(){
    console.log(1111111)
    if(!!!this.userInfo.unitGuid || !!!this.userInfo.userName){
      console.log(22222)
      this.eventService.eventEmitter.emit('userInfo');    //通知用户中心更新用户信息
      return false;
    }
    if(this.notaryCode == ''){
      console.log(33333)
      this.baseUiService.showToast('请选择公证处','customblack','top')
    }else{
      console.log(4444)
      this.router.navigate(['/transaction/goflow'])
      this.NotarizationInfoService.setNotayId(this.notaryCode)
      // this.NotarizationInfoService.setisDaiBan(1)
      if(this.imgList.length!==0){
        this.NotarizationInfoService.setisDaiBan(1)
      }else{
        this.NotarizationInfoService.setisDaiBan(0)
      }
      
    }
  }

  //底部弹出
  async presentActionSheet() {
    const actionSheet = await this.actionSheetController.create({
      header: '上传材料',
      buttons: [ {
        text: '拍照上传',
        icon: 'camera',
        handler: () => {
          this.commService.photo(400,40).subscribe(res=>{
            this.demo(res)
          })
        }
      }, {
        text: '相册上传',
        icon: 'image-outline',
        handler: () => {
          this.commService.picture(300,40).subscribe(res =>{
            this.demo(res)
          })
        }
      }, {
        text: '关闭',
        icon: 'close',
        role: 'cancel',
        handler: () => {
          console.log('关闭');
        }
      }]
    });
    await actionSheet.present();
  }

 

  demo(info:any){
    let _this =this
    this.upphotoService.Uploading(info).then( res1 =>{
      _this.imgList = [..._this.imgList,...res1]
      setTimeout(() => {
        this.cd.detectChanges();
      },200)
    }) 
  }
}
